﻿using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    public class LoginController : Controller
    {
        private readonly AdminUserService _adminUserService;
        private readonly LoginUtil _LoginUtil;
        private readonly LogLoginService _logLoginService;
        public LoginController(LoginUtil LoginUtil, AdminUserService adminUserService, LogLoginService logLoginService)
        {
            _LoginUtil = LoginUtil;
            _adminUserService = adminUserService;
            _logLoginService = logLoginService;
        }

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> IndexAsync()
        {
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            if (result.Succeeded)
                return Redirect("/");
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(LoginDto dto)
        {
            string ip = HttpContextExtension.GetClientUserIp(HttpContext);
            if (dto.Username == null || dto.Password == null)
                return Json(new { status = 0, msg = "用户名密码不能为空！" });            
            AdminUser loginInfo = await _adminUserService.CheckUorP(dto.Username, dto.Password);
            if (loginInfo != null)
            {
                if(loginInfo.Status == false)
                    return Json(new { status = 0, msg = "该用户处于禁用状态" });
                //将用户信息写入COOKIES
                await _LoginUtil.SignInAsync(loginInfo, dto.Remember == "on");
                //更新数据库用户登录状态
                _adminUserService.UpdateLoginInfoAsync(loginInfo.Id, ip);
                //登录日志单独写入
                await _logLoginService.InsertLogLoginAsync(loginInfo.Id, ip);
                return Json(new { status = 1, msg = "登录成功！" });
            }
            else
                return Json(new { status = 0, msg = "用户名密码错误！" });
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> LoginOut()
        {
            await HttpContext.SignOutAsync();
            return Redirect("/Admin/Login/Index");
        }

    }
}
